package com.totoro.zk.cfmc.service.impl ;

import java.io.File ;
import java.io.FileInputStream ;
import java.io.InputStream ;
import java.util.List ;

import org.slf4j.Logger ;
import org.slf4j.LoggerFactory ;

import com.totoro.zk.cfmc.conf.ZKConf ;
import com.totoro.zk.cfmc.ex.UploadConfigurationException ;
import com.totoro.zk.cfmc.model.ConfigurationItem ;
import com.totoro.zk.cfmc.register.CuratorClient ;
import com.totoro.zk.cfmc.service.IConfigurationService ;
import com.totoro.zk.cfmc.util.IOStreamUtils ;

/**
 * @author 80002165 @date 2017年6月6日 下午4:11:33
 */
public class ConfigurationServiceImpl implements IConfigurationService {
    Logger logger = LoggerFactory.getLogger(this.getClass()) ;
    
    @Override
    public boolean uploadConfFile(String path, File file) {
        if (file == null || !file.exists()) {
            throw new UploadConfigurationException(String.format("为节点：%s 添加配置文件失败！，配置文件file不存在！", path)) ;
        }
        try {
            InputStream is = new FileInputStream(file) ;
            return uploadConfFile(path, is) ;
        } catch (Exception e) {
            
            throw new UploadConfigurationException(String.format("为节点：%s 添加配置文件失败", path)) ;
        }
    }
    
    /*
     * @see
     * com.totoro.zk.cfmc.service.IConfigurationService#uploadConfFile(java.
     * lang.String, java.io.InputStream)
     */
    @Override
    public boolean uploadConfFile(String path, InputStream is) {
        byte[] data = IOStreamUtils.readInputStream(is) ;
        if(data == null) throw new UploadConfigurationException("配置文件流没有获得数据！") ;
        return uploadConfFile(path, data) ;
    }
    
    /*
     * @see
     * com.totoro.zk.cfmc.service.IConfigurationService#uploadConfFile(java.
     * lang.String, java.util.List)
     */
    @Override
    public boolean uploadConfFile(String path, List<ConfigurationItem> items) {
        return false ;
    }
    
    /*
     * @see
     * com.totoro.zk.cfmc.service.IConfigurationService#uploadConfFile(java.
     * lang.String, byte[])
     */
    @Override
    public boolean uploadConfFile(String path, byte[] data) {
        try {
            CuratorClient client = CuratorClient.init(ZKConf.address);
            client.createNode(path, data, true) ;
            
            return true ;
        } catch (Exception e) {
            logger.error("上传配置信息失败！",e);
            throw new UploadConfigurationException("向zk服务器上传配置文件失败！") ;
        }
    }
    
}
